package org.hin.programmering1.engine;

import java.awt.Image;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

/**
 * An extension of the Sprite class allowing simple sprite animations
 * 
 * @author Meanz
 */
public class AnimatedSprite extends Sprite {

	/**
	 * Loads an animation from the given parameters
	 * @param speed
	 * @param strings
	 * @return
	 */
	public static AnimatedSprite loadAnimation(float speed, String... strings) {
		Image[] images = new Image[strings.length];
		for(int i=0; i < strings.length; i++) {
			try {
				images[i] = ImageIO.read(new File(strings[i]));
			} catch(IOException iex) {
				iex.printStackTrace();
			}
		}
		return new AnimatedSprite(images, speed);
	}
	
	private Image[] frames; //The frames
	private float speed; //Animation speed
	private int frameIndex;
	private int elapsedTicks;
	
	/**
	 * Constructor
	 * @param frames
	 * @param speed
	 * @param startIndex
	 */
	public AnimatedSprite(Image[] frames, float speed, int startIndex) {
		super(frames[0]);
		this.frames = frames;
		this.speed = speed;
		this.frameIndex = startIndex;
		this.elapsedTicks = 0;
	}
	
	/**
	 * Constructor
	 * @param frames
	 * @param speed
	 */
	public AnimatedSprite(Image[] frames, float speed) {
		this(frames, speed, 0);
	}
	
	/*
	 * Constructor
	 */
	public AnimatedSprite(Image[] frames) {
		this(frames, 0.5f, 0);
	}
	
	/**
	 * Animation logic
	 * Each second is approximately 60-63 ticks/frames
	 * So a speed of 1.0f should be 1 frame per second (lowering the speed will increase the actual speed)
	 * which is equal to 60-63 ticks/frames
	 */
	@Override
	public void onUpdate() {
		if(getImage() != null) {
			elapsedTicks++; //Increment number of elapsed ticks
			
			if(elapsedTicks >= (speed * GameEngine.targetUPS)) { //Check if enough ticks has elapsed to increment the frame index
				
				frameIndex++; //Increment frame index
				if(frameIndex >= frames.length) { //We don't really need the > since it can never go over.
					frameIndex = 0; //Reset
				}
				elapsedTicks -= (speed * GameEngine.targetUPS); //don't set it to 0, because if we lag something will go wrong!
				
				setImage(frames[frameIndex]); //Set the new frame to be rendered
			}
		}
	}
	
}
